package crond

import (
	"context"
	"encoding/json"
	"time"

	"sale-admin/config/mysql"
	"sale-admin/config/redis"
	"sale-admin/internal/app/web/service/robot"
	"sale-admin/internal/define"

	"192.168.1.75/go-pkg/logx"
)

// SaveGoodsClick 保存商品点击量
func SaveGoodsClick() error {
	var goodsClickData robot.UpGoodsClickData
	rdb := redis.NewDB()
	for {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		js, err := rdb.RPop(ctx, define.RedisGoodsClickDataList).Result()
		cancel()
		if err != nil {
			break
		}
		if err := json.Unmarshal([]byte(js), &goodsClickData); err == nil {
			robotClickService := robot.RobotClick{}
			err := robotClickService.UpGoodsClick(context.Background(), mysql.NewDB(), goodsClickData)
			if err != nil {
				logx.Error(context.Background(), "SaveGoodsClick consumer", logx.Err(err))
			}
		}
	}
	return nil
}
